﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZSZ.CommonMVC;
using ZSZ.IService;

namespace ZSZ.AdminWeb.App_Start
{
    public class ZSZAuthorizeFilter : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            
            CheckPermissionAttribute[] permAtts = (CheckPermissionAttribute[])filterContext.ActionDescriptor
                .GetCustomAttributes(typeof(CheckPermissionAttribute), false);
            if (permAtts.Length <= 0)
            {
                return;
            }
            long? userId = (long?)filterContext.HttpContext.Session["LoginUserId"];
            if (userId==null)
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    AjaxResult ajaxResult = new AjaxResult();
                    ajaxResult.Status = "redirect";
                    ajaxResult.Data = "/Main/Login";
                    ajaxResult.ErrorMsg = "没有登录";
                    filterContext.Result = new JsonNetResult { Data = ajaxResult };
                }
                else
                {
                    filterContext.Result = new RedirectResult("~/Main/Login");
                }
                //filterContext.Result = new ContentResult { Content = "Need login!" };
                return;
            }
            IAdminUserService userService = DependencyResolver.Current.GetService<IAdminUserService>();
            foreach (var permAtt in permAtts)
            {
                if (!userService.HasPermission(userId.Value, permAtt.Permission))
                {
                    if (filterContext.HttpContext.Request.IsAjaxRequest())
                    {
                        AjaxResult ajaxResult = new AjaxResult();
                        ajaxResult.Status = "error";
                        ajaxResult.ErrorMsg = "No permission: " + permAtt.Permission;
                        filterContext.Result = new JsonNetResult { Data = ajaxResult };
                    }
                    else
                    {
                        filterContext.Result = new ContentResult { Content = "No permission: " + permAtt.Permission };
                    }
                    return;
                }
            }
        }
    }
}